package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.UserService;

@Controller
public class LoginController extends BaseController {

	private static final long serialVersionUID = 2953245877386975346L;
	
	@Autowired
	private UserService userService;

	@RequestMapping("/showLogin.do")
	public String showLogin(HttpSession session, Model model) {
		if(session.getAttribute(User.LOGGED_IN_USER_KEY) != null){
			return "redirect:/secure/showDashboard.do";
		}
		model.addAttribute("user", new User());
		return "login";
	}
	
	@RequestMapping("/login.do")
	public String login(@ModelAttribute("user") User user, BindingResult result, Model model,
			HttpServletRequest request) throws Exception {
		
		User dbUser = userService.authenticUser(user);
		if(dbUser == null){
			result.reject("error.invaliduser");
			user.setPassword("");
			model.addAttribute("user", user);
			return "loginForm";
		}
		request.getSession().setAttribute(User.LOGGED_IN_USER_KEY, dbUser.getId());
		return "success";
	}
}
